<template>
  <div class="HFileGrabOrUpload-container">
    <HNavbar @click-left="$router.back()">
      <template #right>
        <van-icon name="success" class="HNavbar-icon navicon-sm" @click="handleConfirm">确认</van-icon>
      </template>
    </HNavbar>
    <div class="form">
      <el-form>
        <el-row :gutter="10" justify="space-between">
          <el-col :span="8">
            <el-form-item label="">
              <div style="display: flex">
                <van-space>
                  <el-input v-model="fileNames" disabled></el-input>
                  <van-uploader :max-count="3" multiple :preview-image="false" :after-read="afterRead" accept=".pdf,.PDF" ref="uploaderRef">
                    <el-button type="primary">上传</el-button>
                  </van-uploader>
                </van-space>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件">
              <div style="display: flex; width: 100%">
                <el-select v-model="currentFile" placeholder="请选择文件">
                  <el-option v-for="fileInfo in fileList" :key="fileInfo.fileUrl" :value="fileInfo.fileUrl || '-'" :label="fileInfo.fileName || '-'"></el-option>
                </el-select>
                <el-button @click="handleDelete" style="margin-left: 5px">删除</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div style="display: flex; justify-content: flex-end">
              <el-space wrap size="default">
                <el-checkbox v-model="checkAll" border :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                  <span>全选</span>
                </el-checkbox>
                <el-button @click="handleAssign">一键赋值</el-button>
              </el-space>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div class="content" v-autoHeight :class="{ 'full-screen': state.fullScreenLeft }">
        <div class="left">
          <div class="title">
            <span>记录</span>
            <ElIcon @click="state.fullScreenLeft = !state.fullScreenLeft"><i-ep-View /></ElIcon>
          </div>
          <div>
            <HPDFViewer :path="state.path"></HPDFViewer>
          </div>
        </div>
        <div class="right">
          <div class="title">
            <span>项目</span>
          </div>
          <div ref="genericDiv">
            <HGenericForm v-model:fields="state.attributesFields" @handle-event="handleEvent" :disabled="true" :showCheckbox="true"></HGenericForm>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="HFileGrabOrUpload">
import { deleteEquipFile, getConfigAttributesText, getEquipmentFileSelect, uploadEquipmentFile } from '@/api/base';
import { GetCommRecordAttributes, type RecordAttributeItem } from '@/api/instrumentManage';
import HGenericForm from '@/components/HGenericForm/index.vue';
import HPDFViewer from '@/components/HPDFViewer/index.vue';
import { useMainStore } from '@/store';
import { useFileGrabOrUploadStore } from '@/store/modules/fileGrabOrUpload';
import { generateTimestampedUUID } from '@/utils/dateTools';
import { type UploaderFileListItem, type UploaderInstance, closeToast, showConfirmDialog, showLoadingToast, showToast } from 'vant';
import { computed, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const uploaderRef = ref<UploaderInstance>();
const router = useRouter();
const route = useRoute();
const mainStore = useMainStore();
const title = route.meta.title as string;
type FileListType = {
  attachmentId: string;
  fileExtension: string;
  fileName: string;
  fileUrl: string;
};
const fileList = ref<FileListType[]>([]);
const badge = computed(() => mainStore.signalValue);
const token = localStorage.getItem('tokenKey');
const formOptions = ref<RecordAttributeItem[]>([]);
const fileNames = computed(() => {
  return fileList.value.map((item) => item.fileName).join(',');
});

const FileGrabOrUploadStore = useFileGrabOrUploadStore();
const testRouteParams = FileGrabOrUploadStore.pageParams;

const currentFile = ref('');
const checkAll = ref(false);
const checkedValues = computed(() => {
  return state.attributesFields.filter((item) => item.checked).map((item) => item.code);
});
const isIndeterminate = ref(false);
const state = reactive({
  recordCode: '',
  recordOptions: [],
  recordProps: {
    label: 'name',
    children: 'children'
  },
  fullScreenLeft: false,
  path: '',
  attributesFields: [] as RecordAttributeItem[],
  areaTree: [],
  areaProps: {
    label: 'name',
    children: 'children'
  },
  storeOptions: [],
  areaOptions: [],
  pdfUrl: '',
  pdfContentUUID: generateTimestampedUUID(),
  pdfShow: false,
  nodeRow: {
    flowCode: ''
  },
  backData: []
});

watch(
  () => currentFile.value,
  (val) => {
    let currentFileInfo = fileList.value.find((item) => item.fileUrl === val);
    // alert('监听到文件变化：' + JSON.stringify(currentFileInfo));
    state.path = currentFileInfo?.fileUrl || '';
    // console.log('state.path', state.path);
    // alert('渲染pdf地址：' + JSON.stringify(state.path));
  }
);

async function afterRead(files: UploaderFileListItem | UploaderFileListItem[]) {
  console.log('afterRead', files);
  let param = new FormData(); //创建form对象
  if (files instanceof Array) {
    files.forEach((item) => {
      if (item.file) param.append('txt_fileDocument', item.file);
    });
  } else {
    files.file && param.append('txt_fileDocument', files.file);
  }
  if (token) param.append('Token', token);
  param.append('type', 'TestPdf');
  param.append('batchID', testRouteParams.batchID);
  param.append('materialCode', testRouteParams.materialCode);
  param.append('recordCode', testRouteParams.recordCode);
  param.append('testID', testRouteParams.testID);
  logFormData(param);
  showLoadingToast({
    message: '上传中...',
    forbidClick: true,
    duration: 0
  });
  try {
    const result = await uploadEquipmentFile(param);
    closeToast();
    if (result.httpCode === 0) {
      if (files instanceof Array) {
        files.forEach((item) => {
          item.status = 'done';
        });
      } else {
        files.status = 'done';
      }
      showToast('上传文件成功');
      getFileSelect();
    }
  } catch (error) {
    showToast((error as Error).message);
  }
}

// 获取文件下拉选框
async function getFileSelect() {
  const result = await getEquipmentFileSelect(testRouteParams);
  console.log(result);
  if (result.httpCode === 0) {
    fileList.value = result.result;
    //     alert('获取文件列表' + JSON.stringify(result.result));
    if (!currentFile.value) currentFile.value = fileList.value[0]?.fileUrl;
  }
}

// 全选change
function handleCheckAllChange(val: boolean) {
  state.attributesFields.forEach((item) => {
    item.checked = val;
  });
}

// 表单事件接收
function handleEvent(_, type: string) {
  if (type == 'checkbox') {
    setIsIndeterminate();
  }
}

function setIsIndeterminate() {
  const checkedCount = checkedValues.value.length;
  checkAll.value = checkedCount === state.attributesFields.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < state.attributesFields.length;
}

// 获取表单项
async function getFormOptions() {
  const result = await GetCommRecordAttributes({
    testID: testRouteParams.testID,
    recordCode: testRouteParams.recordCode,
    testStandard: testRouteParams.testStandard
  });
  // console.log(result);
  if (result.httpCode === 0) {
    formOptions.value = result.result.filter((e) => e.type === 'PDF');
    // console.log(JSON.stringify(formOptions.value));
    state.attributesFields = formOptions.value;
    console.log(state.attributesFields);
    for (let w = 0; w < state.attributesFields.length; w++) {
      state.attributesFields[w].checked = true;
    }
    setIsIndeterminate();
  }
}

// 一键赋值
async function handleAssign() {
  let currentFileInfo = fileList.value.find((item) => item.fileUrl === currentFile.value);
  let attachmentId = currentFileInfo?.attachmentId || '';
  try {
    let params = {
      attachmentID: attachmentId,
      pdfAttributes: state.attributesFields.map((e) => ({
        attributeCode: e.code,
        attributeValue: e.value || '',
        line: e.line
      }))
    };
    console.log(state.attributesFields);
    const result = await getConfigAttributesText(params);
    if (result.httpCode === 0) {
      if (result.result && result.result.data) {
        result.result.data.forEach((e) => {
          let flag = state.attributesFields.find((a) => a.code === e.attributeCode);
          if (flag) flag.value = e.attributeValue;
        });
      }
    }
    showToast(result.message);
  } catch (error) {
    showToast((error as Error).message);
  }
}

function handleDelete() {
  showConfirmDialog({ message: '确认删除吗？' }).then(async () => {
    let currentFileInfo = fileList.value.find((item) => item.fileUrl === currentFile.value);
    let attachmentId = currentFileInfo?.attachmentId || '';
    const result = await deleteEquipFile({
      attachmentId: attachmentId
    });
    if (result.httpCode === 0) {
      currentFile.value = '';
      getFileSelect();
    }
    showToast(result.message);
  });
}

function handleConfirm() {
  FileGrabOrUploadStore.SET_RETURN_PARAMS(state.attributesFields);
  router.back();
}

function logFormData(formData: FormData) {
  for (let [key, value] of formData.entries()) {
    console.log(key, value);
  }
}
getFormOptions();
getFileSelect();
</script>

<style scoped lang="scss">
.HFileGrabOrUpload-container {
  height: 100%;

  .form {
    // height: calc(100% - 1rem);
    padding: 5px 10px;
  }
}

.content {
  // height: calc(100% - 1.2rem);
  --transition: all 0.3s ease;
  display: flex;
  flex: 1;
  // padding: 10px 20px;
  overflow: hidden;
  position: relative;
  box-sizing: border-box;
  justify-content: space-between;
  transition: var(--transition);

  .left,
  .right {
    z-index: 1;
    display: flex;
    flex-shrink: 0;
    flex-direction: column;
    border: 1px solid var(--el-color-primary);
    border-radius: var(--el-border-radius-base);
    transition: var(--transition);
    box-sizing: border-box;
    overflow: hidden;
    width: calc(50% - 10px);

    .title {
      font-size: var(--vt-ft-md);
      font-weight: 600;
      background-color: var(--el-color-primary);
      padding: 8px;
      color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .el-icon {
        font-size: var(--vt-ft-md);
      }
    }

    > div:nth-child(2) {
      flex: 1;
      display: flex;
      overflow: auto;
    }
  }

  .left {
    // margin-right: ;
  }

  &.full-screen {
    margin: 0;
    // margin-top: var(--van-nav-bar-height);
    // padding: 0 20px;

    .left {
      background-color: #fff;
      width: 100%;
      height: 100vh;
    }

    .right {
      // animation: hide 5s ease forwards;
      transform: translateX(100%);

      > * {
        display: none;
      }
    }
  }
}
</style>
